package cn.xcyy.itcc.service.impl;

import cn.xcyy.itcc.constants.RedisCourseTypeConstants;
import cn.xcyy.itcc.domain.CourseType;
import cn.xcyy.itcc.mapper.CourseTypeMapper;
import cn.xcyy.itcc.service.ICourseTypeService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程目录 服务实现类
 * </p>
 *
 * @author whale
 * @since 2022-09-30
 */
@Service
public class CourseTypeServiceImpl extends ServiceImpl<CourseTypeMapper, CourseType> implements ICourseTypeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @Cacheable(cacheNames = RedisCourseTypeConstants.COURSE_TYPE_TREE_DATA_CACHENAMES,key = RedisCourseTypeConstants.COURSE_TYPE_TREE_DATA_KEY)
    public List<CourseType> treeData() {

        Object obj = redisTemplate.opsForValue().get(RedisCourseTypeConstants.COURSE_TYPE_TREE_DATA_CACHENAMES);

        return tree();
    }

    private List<CourseType> tree() {
        //查询所有分类
        List<CourseType> courseTypes = selectList(null);

        Map<Long, CourseType> courseTypeMap = courseTypes.stream().collect(Collectors.toMap(CourseType::getId, courseType -> courseType));

        List<CourseType> treeDate = new ArrayList<>();
        courseTypes.forEach(e -> {
            if (e.getId() != null && e.getId().intValue() == 0){
                treeDate.add(e);
            }else {
                CourseType courseType = courseTypeMap.get(e.getPid());
                if (courseType != null){
                    courseType.getChildren().add(e);
                }
            }
        });
        return treeDate;
    }

    @Override
    public boolean deleteById(Serializable id) {
        return super.deleteById(id);
    }

    @Override
    public boolean updateById(CourseType entity) {
        return super.updateById(entity);
    }

    @Override
    public boolean insert(CourseType entity) {
        return super.insert(entity);
    }
}
